package com.ruoyi.aitcommon.controller;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateTime;
import com.ruoyi.aitapp.utils.APPConfigUtils;
import com.ruoyi.aitcommon.utils.ObjUtils;
import com.ruoyi.aitcommon.utils.RuntimeManager;
import com.ruoyi.aitcommon.vo.RuntimeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.api.FlowOperation;
import com.ruoyi.aitcommon.config.ConfigInfoVO;
import com.ruoyi.aitcommon.config.ConfigManager;
import com.ruoyi.aitcommon.utils.FileUtils;
import com.ruoyi.aitcommon.utils.JSONResult;

import cn.hutool.core.util.StrUtil;

/**
 * 在SecurityConfig类中配置,跳过鉴权
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/aitcommon/aitconfig")
public class AitConfigController {
	@Autowired
	ConfigManager configManager;
	@Autowired
	APPConfigUtils appConfigUtils;
	@Autowired
	FlowOperation flowOperation;
	@Autowired
	RuntimeManager runtimeManager;
	@Value("${ait.path}")
	String aitPath;
	
	/**
	 * 配置文件查询
	 * 增加运行环境信息
	 * @param queryVO
	 * @return
	 */
	@GetMapping("/list")
    public JSONObject list(ConfigInfoVO queryVO)
    {
		List<Map<String,Object>> retlist=new ArrayList<>();
        try {
//			依据查询条件获取配置信息
        	List<ConfigInfoVO> list = configManager.getConfigInfoList(queryVO);
			if(ObjUtils.isBlank(list)) return JSONResult.success(retlist);

//			构造返回值
			for (ConfigInfoVO vo : list) {
				Map<String,Object> retmap=new LinkedHashMap<>();
				retmap.put("flowCode",vo.getFlowCode());
				retmap.put("parmname",vo.getParmname());
				retmap.put("zwName",vo.getZwName());
				retmap.put("type",vo.getType());
				retmap.put("path",vo.getPath());
				retmap.put("dir",vo.getDir());
				retmap.put("filename",vo.getFilename());
				retmap.put("desc",vo.getDesc());
				final RuntimeVO runInfo = runtimeManager.getRunInfo(vo.getFlowCode());
				if(runInfo!=null){
//						补充运行信息
					retmap.put("flowID",String.valueOf(runInfo.getFlowID()));
					retmap.put("status",runInfo.getStatus());
					retmap.put("statusName",runInfo.getStatusName());
					retmap.put("logStatus",runInfo.getLogStatus());
					retmap.put("runTime",runInfo.getRunTime());
					DateTime date1=new DateTime(runInfo.getStartTime());
					DateTime date2=new DateTime(runInfo.getEndTime());
					retmap.put("startTime",date1.toString());
					retmap.put("endTime",date2.toString());
				}
//				依据查询条件过滤
				if(queryVO.getIsRun()&&runInfo==null)
					continue;

				retlist.add(retmap);
			}

        	return JSONResult.success(retlist);
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }
	
	@GetMapping("/dir")
    public JSONObject getDir()
    {
        try {
        	List<String> dirs = configManager.getDirs();
        	return JSONResult.success(dirs);
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }
	
	/**
	 * 加载所有JSON配置文件
	 * @return
	 */
	@GetMapping("/reload")
    public JSONObject reload()
    {
        try {
        	configManager.loadConfig();
			appConfigUtils.buildParam();
        	return JSONResult.success("配置文件加载完成!");
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }
	
	/**
	 * 手工触发Flow
	 * @param flowCode
	 * @return
	 */
	@GetMapping("/run")
    public JSONObject runFlow(String flowCode)
    {
        try {
//			调用Flow的api
			final JSONObject ret = flowOperation.templateAsync(flowCode, 0, new String[0]);
//			因为是异步调用,等待1秒返回
//			Thread.sleep(1000);
			return ret;
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }
	
	/**
	 * 读取日志文件
	 * @param type
	 * @param num
	 * @return
	 */
	@GetMapping("/loadLogFile")
    public JSONObject loadLogFile(String type,int num)
    {
        try {
        	String path=this.aitPath;
//        	如果配置文件中未设置路径,获取当前用户运行路径
        	if(StrUtil.isBlank(path)) {
        		path=System.getProperty("user.dir");
        	}
        	path+="\\logs";
        	if(type.equals("common")) {
        		path+="\\ait-common.log";
        	}else if(type.equals("error")) {
        		path+="\\sys-error.log";
        	}else if(type.equals("http")) {
        		path+="\\ait-http.log";
        	}else if(type.equals("sql")) {
        		path+="\\ait-sql.log";
        	}else {
        		return JSONResult.success();
        	}

			Charset charset = Charset.forName("GBK");
        	String lines = FileUtils.readFileLines(path,num, charset);
        	
//        	处理返回
        	Map<String,Object> retmap=new LinkedHashMap<String,Object>();
        	retmap.put("path", path);
        	retmap.put("text", lines);
        	return JSONResult.success(retmap);
        	
        }catch(Exception ex) {
        	return JSONResult.error(ex.getMessage());
        }
    }
}
